<template>
  <div class="image-show-comp" :style="styleScreen" v-on="$listeners">
    <img v-show="name" :src="ImageObject[imgKey]" alt="" v-bind="$attrs" />
  </div>
</template>
<script>
// 自定义图片组件
const requireImgs = require.context(
  '../../../assets/images',
  true,
  /^\S+\.(png|jpg|jpeg|gif)$/,
);
const ImageObject = {};
requireImgs.keys().map((i) => {
  ImageObject[i.split('.')[1]] = requireImgs(i);
});

/**
 * ImageShow-图片文件  2021/11/25
 * @author xu
 * @param {String} width 宽度
 * @param {String} height 高度
 * @param {String} type 类型 -> icon/bg
 * @param {String} name 图片路径 -> warningPage/env
 * eg: <image-show name="warningPage/env" width="30px" height="40px"></image-show>
 */
export default {
  name: 'ImageShow',
  props: {
    width: {
      type: [String, Number],
      default: '80px',
    },
    height: {
      type: [String, Number],
      default: '80px',
    },
    type: {
      type: String,
      default: 'icon',
    },
    name: {
      type: String,
      required: true,
    },
  },
  data() {
    return { ImageObject };
  },
  computed: {
    imgKey() {
      return `/${this.type}/${this.name}`;
    },
    styleScreen() {
      const width = isNaN(Number(this.width)) ? this.width : this.width + 'px';
      const height = isNaN(Number(this.height))
        ? this.height
        : this.height + 'px';
      return {
        width,
        height,
      };
    },
  },
};
</script>
<style lang="scss" scoped>
.image-show-comp {
  img {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
}
</style>
